package com.youlai.system.controller;


import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.youlai.system.common.result.Result;
import com.youlai.system.model.entity.Attendancerecord;
import com.youlai.system.model.form.AttendUpdateStatusForm;
import com.youlai.system.model.query.AttendanceQuery;
import com.youlai.system.model.query.EmployQuery;
import com.youlai.system.model.vo.AttendanceRecordVO;
import com.youlai.system.model.vo.EmployExportVO;
import com.youlai.system.service.IAttendancerecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhi1
 * @since 2024-05-28
 */
@RestController
@RequestMapping("/api/v1/attendancerecord") // 修改路径为 "/api/v1/attendancerecord"
@Tag(name = "11.考勤管理接口")
@RequiredArgsConstructor
public class AttendancerecordController {

    private final IAttendancerecordService attendancerecordService;

    @Operation(summary = "考勤信息列表")
    @GetMapping("/list")
    public Result<PageInfo<AttendanceRecordVO>> getAttendanceRecords(@ParameterObject AttendanceQuery attendanceQuery){
        PageInfo<AttendanceRecordVO> result = attendancerecordService.getAttendPage(attendanceQuery);
        return Result.success(result);
    }

    @Operation(summary = "修改考勤状态")
    @PostMapping("/updateStatus")
    public Result updateStatus(@RequestBody AttendUpdateStatusForm attendUpdateStatusForm){
        Integer id = attendancerecordService.updateAttendUpdateStatus(attendUpdateStatusForm);
        return Result.success(id);
    }

    @Operation(summary = "导出考勤")
    @GetMapping("/_export")
    public void exportAttendance(AttendanceQuery attendanceQuery, HttpServletResponse response) throws IOException {
        String fileName = "考勤列表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        List<AttendanceRecordVO> attendanceRecordVOList = attendancerecordService.getList();
        List<Attendancerecord> flattenedAttendanceList = new ArrayList<>();

        for (AttendanceRecordVO record : attendanceRecordVOList) {
            for (Attendancerecord attendance : record.getAttendancerecordList()) {
                flattenedAttendanceList.add(attendance);
            }
        }

        EasyExcel.write(response.getOutputStream(), Attendancerecord.class).sheet("考勤列表").doWrite(flattenedAttendanceList);

    }



}

